package DEEPERsource.DEEPERsource.source.controllers;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Iterator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import parser.Parser;
import parser.StanfordParser;
import parser.stanfordparser.StanfordParserWrapper;
import preprocessing.DefaultPreprocessor;
import preprocessing.SimplePreprocessor;
import corpus.Text;
import corpus.ppi.CorpusFactory;
import deeper.Interaction;
import exceptions.GraphException;
import exceptions.NoSuchWordException;

/**
 * "Thing for its own". Service application that runs a parser over dataset and
 * serialize results in order to speed up execution of machine learning part. 
 * @author tfayruzo
 *
 */
public class ParseSerializer {
	private static Log _log = LogFactory.getLog(ParseSerializer.class);

	public void run(String sourceXML, String outDir){
		CorpusFactory cFactory = new CorpusFactory();
		//Text corpus = cFactory.getCorpusFromPPIXML(sourceXML, new SimplePreprocessor());
		Text corpus = cFactory.getCorpusFromPPIXML(sourceXML, new DefaultPreprocessor());
		Parser stanfordParser = new StanfordParser();
		stanfordParser.init("-maxLength","200","-dependencyType","typedDependenciesCCprocessed");
		for(Iterator<Interaction> i = corpus.interactions().iterator(); i.hasNext();){
			Interaction inter = i.next();
			_log.debug(inter.sentence);
			if(inter.predefinedStatus != null){
				//do not parse some interactions, as we guessed its class on preprocessing step
			}else{
				try{
					stanfordParser.parse(inter.sentence);
					inter.parseTree = stanfordParser.getParseTree();
					inter.depTree = stanfordParser.getDependencyTree();
					inter.struct = stanfordParser.getStructuredSentence();
					inter.initInteraction();
				} catch (NoSuchWordException e) {
					_log.error(e.getMessage());
				} catch (GraphException e) {
					_log.error("Can't define path for interaction between "
						+ inter.p1.name + " and " + inter.p2.name);
					_log.error("Nested exception:" + e.getClass() + ":"
						+ e.getMessage());
				}catch(UnsupportedOperationException e){
					_log.error("Nested exception message: "+e.getMessage());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			ObjectOutputStream out = null;
			try{
				File file = new File(outDir+inter.id);
				if(file.exists()){
					file.delete();
				}
				file.createNewFile();	
				out = new ObjectOutputStream(new FileOutputStream(file));
				out.writeObject(inter);				
			}catch(IOException e){
				e.printStackTrace();
			}finally{
				try {
					if(out!=null)
						out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			inter.erase();
		}
	}
}
